package com.tju.t5.dao.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.tju.t5.dao.IUserDAO;
import com.tju.t5.entity.User;

public class UserDAO extends HibernateDaoSupport implements IUserDAO {

	private static final Logger log = LoggerFactory.getLogger(UserDAO.class);
	
	@Override
	public void createUser(User user) {
		log.debug("saving User instance");
		try
		{
			getHibernateTemplate().save(user);
			log.debug("save successfully");
		}
		catch(RuntimeException ex)
		{
			log.error("save failed", ex);
			throw ex;
		}
	}

	@Override
	public void updateUser(User user) {
		log.debug("udpating User instance");
		try
		{
			getHibernateTemplate().update(user);
			log.debug("update successfully");
		}
		catch(RuntimeException ex)
		{
			log.error("update failed", ex);
			throw ex;
		}

	}

	@Override
	public void deleteUser(User user) {
		log.debug("deleting User instance");
		try
		{
			getHibernateTemplate().delete(user);
			log.debug("delete successfully");
		}
		catch(RuntimeException ex)
		{
			log.error("delete failed", ex);
			throw ex;
		}

	}

	@Override
	public User findUserByID(int userID) {
		log.debug("getting User instance with id: " + userID);
		try
		{
			User user = getHibernateTemplate().get(User.class, userID);
			return user;
		}
		catch(RuntimeException ex)
		{
			log.error("get failed", ex);
			throw ex;
		}
		
	}

	@Override
	public User findUserByUsername(String username) {
		log.debug("finding User instance with username: " + username);
		try
		{
			User user = new User();
			user.setUsername(username);
			
			@SuppressWarnings("unchecked")
			List<User> users = this.getHibernateTemplate().findByExample(user);
			
			if(users.size() > 0)
			{
				user = users.get(0);
				return user;
			}
			else
			{
				return null;
			}
		}
		catch(RuntimeException ex)
		{
			log.error("finding user failed", ex);
			throw ex;
		}
	}

}
